<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
          >{{ item.meta.title }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="container">
      <div>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          status-icon
        >
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="ruleForm.title" />
          </el-form-item>
          <el-form-item label="文章简述" prop="desc">
            <el-input v-model="ruleForm.desc" />
          </el-form-item>
          <el-form-item label="文章类型" prop="articleCategory">
            <el-radio-group v-model="ruleForm.articleCategory">
              <el-radio :label="0" size="large">0-景点介绍</el-radio>
              <el-radio :label="1" size="large">1-景点游记</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input v-model="ruleForm.author" />
          </el-form-item>
          <el-form-item label="文章图片" prop="titleImageUrl">
            <!--  <el-input v-model="ruleForm.titleImageUrl" />-->
            <!--  -->
            <el-upload
              action="#"
              :multiple="false"
              accept=".jpg,.jpeg,.png,.svg"
              :limit="1"
              :show-file-list="true"
              list-type="picture-card"
              @change="handelFileChange"
              @mouseleave="handelFileMouseleave"
            >
              <el-image class="avatar" v-if="imageUrl" :src="imageUrl" />
              <el-icon v-else><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="文章内容" prop="content" type="textarea">
            <button @click="uploadimg">上传所有图片</button>
            <mavon-editor
              v-model="ruleForm.content"
              style="width: 100%"
              ref="md"
              @imgAdd="$imgAdd"
              @imgDel="$imgDel"
            />
            
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >新增</el-button
        >
        <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      </div>
    </div>
  </div>
</template>
  <script>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElNotification } from "element-plus";
export default {
  setup() {
    //文章标题图片 获取文件数据
    const selectedFile=ref()
    const imageUrl = ref("");
    const router = useRouter();
    const handelFileChange = (file) => {
      selectedFile.value = file.raw;
      imageUrl.value = URL.createObjectURL(file.raw);
    };
    //富文本编辑器
    const md = ref(null);
    let img_file = {};
    const $imgAdd = (pos, $file) => {
      // 缓存图片信息
      img_file[pos] = $file;
    };
    const $imgDel = (pos) => {
      delete img_file[pos];
    };
    const uploadimg = ($e) => {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData();
      for (var _img in img_file) {
        formdata.append("files", img_file[_img]);
      }
      request
        .request({
          url: "/article/imageAdd",
          method: "post",
          data: formdata,
          headers: { "Content-Type": "multipart/form-data" },
        })
        .then((res) => {
          const paths = res.data.data.payload;

          /**
           * 例如：返回数据为 res = [[pos, url], [pos, url]...]
           * pos 为原图片标志（0）
           * url 为上传后图片的url地址
           */
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
          for (let index = 0; index < paths.length; index++) {
            md.value.$img2Url(index + 1, paths[index]);
          }
        });
    };

    let breadList = []; // 路由集合
    const route = useRoute();

    const getBreadcrumb = (url) => {
      let matched = url.matched;
      //如果不是首页
      if ("Home" == matched[0].name) {
        matched[0].meta = { title: "系统首页" };
      }
      breadList = matched;
    };
    watch(
      route,
      (newValue, oldValue) => {
        // console.log(222222,newValue)
        getBreadcrumb(newValue);
      },
      { deep: true, immediate: true }
    );

    const resetForm = (formEl) => {
      if (!formEl) return;
      formEl.resetFields();
    };
    const image=ref("");
    const submitForm = async (formEl) => {
      await formEl.validate((valid, fields) => {
        if (valid) {
                //上传图片
      var formdata = new FormData();
        formdata.append("imagefile", selectedFile.value);
        request
        .request({
          url: "/article/aimage",
          method: "post",
          data: formdata,
          headers: { "Content-Type": "multipart/form-data" },
        })
        .then((res) => {
          image.value = res.data.data.payload;
          request
            .request({
              url: "/article/add",
              method: "post",
              data: {
                title: ruleForm.title,
                desc: ruleForm.desc,
                author: ruleForm.author,
                content: ruleForm.content,
                articleCategory: ruleForm.articleCategory,
                titleImageUrl: image.value[0] ,
              },
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: "上传成功",
                  message: "成功上传文章",
                });
                router.push('articleInfo')
              } else {
                ElNotification({
                  title: "更新失败",
                  message: "请联系管理员检查失败原因",
                });
              }
            })
            .catch((e) => {
              ElNotification({
                title: "更新失败",
                message: "请联系管理员检查失败原因",
              });
            });
         
        });

  } else {
          ElNotification({
            title: "校验失败",
            message: "请重新填写信息",
          });
        }
      });
    };

    const ruleForm = reactive({
      title: "",
      desc: "",
      author: "",
      content: "",
      articleCategory: 0,
      titleImageUrl: null,
    });
    const rules = reactive({
      title: [
        {
          required: true,
          message: "请输入标题",
          trigger: "blur",
        },
      ],
      desc: [
        {
          required: true,
          message: "请输入简述",
          trigger: "blur",
        },
      ],
      content: [
        {
          required: true,
          message: "请输入文章内容",
          trigger: "blur",
        },
      ],
      author: [
        {
          required: false,
          message: "请输入文章作者",
          trigger: "blur",
        },
      ],
      articleCategory: [
        {
          required: true,
          message: "请选择用户类型",
          trigger: "change",
        },
      ],
    });
    const ruleFormRef = ref();
    const centerDialogVisible = ref(false);
    return {
      breadList,
      resetForm,
      ruleFormRef,
      submitForm,
      ruleForm,
      rules,
      centerDialogVisible,
      uploadimg,
      handelFileChange,
      imageUrl,
      $imgAdd,
      $imgDel,
      md,
      selectedFile,
      image
      
    };
  },
};
</script>

  <style lang="scss" sco
  ped>
.handle-box {
  margin-bottom: 20px;
}
.handle-select {
  width: 120p;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.el-upload--text {
  height: auto;
  width: auto;
}
.mavonEditor {
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}
</style>
  